/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileManagers;

import java.io.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Tudor
 */
public class FileUploadController {

    UploadedFile file;

    public FileUploadController() {
    }

    //for automatic uploading
    public void handleTreeUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void handleWebUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        file = event.getFile();
       
        File xml = convert(file);
        HTMLController htmlParser = new HTMLController();
        htmlParser.parseToHTML(xml);//generate the xhtml file here
    }

    private File convert(UploadedFile file) {
        File xml = null;
        try {
            xml = new File("uploadedTree");
            FileInputStream fis = (FileInputStream) file.getInputstream();

            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            BufferedWriter out = new BufferedWriter(new FileWriter(xml));

            String line;
            while ((line = in.readLine()) != null) {
                // Print the content on the console
                out.write(line);
                out.newLine();
            }
        } catch (Exception exc) {
            System.out.println("Could not convert file");
        }

        return xml;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public void upload() {
        FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
}
